import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user.js'

// 懒加载路由组件
const Login = () => import('../views/login.vue')
const AdminLayout = () => import('../views/Header.vue')

// 子路由组件
const Dashboard = () => import('../views/Dashboard.vue')
const EventList = () => import('../views/EventList.vue')
const EventCreate = () => import('../views/EventCreate.vue')
const EventCategories = () => import('../views/EventCategories.vue')
const UserManagement = () => import('../views/UserManagement.vue')

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'AdminLayout',
      component: AdminLayout,
      // redirect: '/dashboard', // 默认重定向到仪表盘
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: Dashboard,
          meta: {
            title: '仪表盘 - Bit Event',
            requiresAuth: true
          }
        },
        {
          path: 'events/list',
          name: 'EventList',
          component: EventList,
          meta: {
            title: '活动列表 - Bit Event',
            requiresAuth: true
          }
        },
        {
          path: 'events/create',
          name: 'EventCreate',
          component: EventCreate,
          meta: {
            title: '创建活动 - Bit Event',
            requiresAuth: true
          }
        },
        {
          path: 'events/categories',
          name: 'EventCategories',
          component: EventCategories,
          meta: {
            title: '活动分类 - Bit Event',
            requiresAuth: true
          }
        },
        {
          path: 'users/list',
          name: 'UserManagement',
          component: UserManagement,
          meta: {
            title: '用户管理 - Bit Event',
            requiresAuth: true
          }
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: {
        title: '登录 - Bit Event'
      }
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || 'Bit Event'
  
  // 获取用户store
  const userStore = useUserStore()
  
  // 权限控制
  if (to.meta.requiresAuth) {
    // 使用store检查登录状态
    if (!userStore.isLoggedIn) {
      console.log('未登录，跳转到登录页')
      // 未登录，跳转到登录页
      next({ path: '/login', query: { redirect: to.fullPath } })
    } else {
      // 已登录，继续访问
      next()
    }
  } else {
    // 如果是登录页面且已登录，跳转到首页
    if (to.path === '/login' && userStore.isLoggedIn) {
      next({ path: '/dashboard' })
    } else {
      // 不需要登录的页面，直接访问
      next()
    }
  }
})

export default router
